package qingxin.servlet.admin.journalist;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import qingxin.dao.JournalistDAO;
import qingxin.dao.PhotoDAO;
import qingxin.factory.DAOFactory;
import qingxin.servlet.admin.AdminServlet;
import qingxin.vo.Journalist;

@WebServlet("/admin/journalist/getAll")
public class GetAllJournalistServlet extends AdminServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private JournalistDAO journalistDAO;
	private PhotoDAO photoDAO;
	
	public GetAllJournalistServlet(){
		super();
		journalistDAO = DAOFactory.getJournalistDAO();
		photoDAO = DAOFactory.getPhotoDAO();
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
    	response.setContentType("text/html; charset=utf-8");
    	response.setCharacterEncoding("utf-8");
		PrintWriter writer = response.getWriter();
		
		if(!verification(request)){
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			return;
		}
		
		try{
			JSONObject jsonResult = new JSONObject();
			Journalist[] journalists = journalistDAO.getAll();
			JSONArray jsonJournalists = new JSONArray();
			
			for(Journalist journalist : journalists){
				JSONObject jsonJournalist = new JSONObject();
				jsonJournalist.put("id", journalist.getJournalistID());
				jsonJournalist.put("name", journalist.getName());
				jsonJournalist.put("class", journalist.getClassName());
				jsonJournalist.put("constellation", journalist.getConstellation());
				jsonJournalist.put("sex", journalist.getSex());
				jsonJournalist.put("motto", journalist.getMotto());
				jsonJournalist.put("avatar", photoDAO.getByID(journalist.getAvatarID()).getAvatarAddress());
				jsonJournalist.put("avatarID", journalist.getAvatarID());
				jsonJournalist.put("introduction", journalist.getIntroduction());
				jsonJournalist.put("birthday", journalist.getBirthday());
				jsonJournalist.put("isRetired", journalist.isRetired());
				jsonJournalist.put("avatarID", journalist.getAvatarID());
				jsonJournalists.put(jsonJournalist);
			}
			
			jsonResult.put("journalists", jsonJournalists);
			writer.println(jsonResult.toString());
			response.setStatus(HttpServletResponse.SC_OK);
		}
		catch(Exception e){
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			writer.println("{\"msg\":\"wrong\"}");
		}
		finally{
			writer.flush();
			writer.close();
		}
	}
}
